package com.uduemc.biso.node.module.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.uduemc.biso.node.core.entities.HBackupSetup;
import com.uduemc.biso.node.module.mapper.HBackupSetupMapper;
import com.uduemc.biso.node.module.service.HBackupSetupService;

import cn.hutool.core.date.DateUtil;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class HBackupSetupServiceImpl implements HBackupSetupService {

	@Autowired
	private HBackupSetupMapper hBackupSetupMapper;

	@Override
	public HBackupSetup insert(HBackupSetup hBackupSetup) {
		hBackupSetupMapper.insert(hBackupSetup);
		return findOne(hBackupSetup.getId());
	}

	@Override
	public HBackupSetup insertSelective(HBackupSetup hBackupSetup) {
		hBackupSetupMapper.insertSelective(hBackupSetup);
		return findOne(hBackupSetup.getId());
	}

	@Override
	public HBackupSetup updateByPrimaryKey(HBackupSetup hBackupSetup) {
		hBackupSetupMapper.updateByPrimaryKey(hBackupSetup);
		return findOne(hBackupSetup.getId());
	}

	@Override
	public HBackupSetup updateByPrimaryKeySelective(HBackupSetup hBackupSetup) {
		hBackupSetupMapper.updateByPrimaryKeySelective(hBackupSetup);
		return findOne(hBackupSetup.getId());
	}

	@Override
	public HBackupSetup findOne(long id) {
		return hBackupSetupMapper.selectByPrimaryKey(id);
	}

	@Override
	synchronized public HBackupSetup findByHostIdIfNotAndCreate(long hostId) {
		Example example = new Example(HBackupSetup.class);

		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);

		PageHelper.startPage(1, 1);
		HBackupSetup selectOneByExample = hBackupSetupMapper.selectOneByExample(example);
		if (selectOneByExample != null) {
			return selectOneByExample;
		}

		HBackupSetup hBackupSetup = new HBackupSetup();
		hBackupSetup.setHostId(hostId).setType((short) 0).setRetain(3).setMonthly(1).setWeekly(1).setDaily(3).setStartAt(null);
		return insert(hBackupSetup);
	}

	@Override
	public List<HBackupSetup> findAllByNoType0AndStartAtNow() {
		Example example = new Example(HBackupSetup.class);

		Criteria criteria = example.createCriteria();
		criteria.andNotEqualTo("type", (short) 0);
		criteria.andLessThanOrEqualTo("startAt", DateUtil.today());

		return hBackupSetupMapper.selectByExample(example);
	}

}
